<template>
  <div>
    <MyTable :goodsList="goodsList">
      <template>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{item,index}">
        <td>{{ index + 1 }}</td>
        <td>{{ item.goods_name }}</td>
        <td>￥{{ item.goods_price }}</td>
        <td>
          <input
            v-if="item.inputVisible"
            class="tag-input form-control"
            type="text"
            v-fouce
            @blur="LostFocus(item)"
            @keyup.enter="add($event, item)"
            @keyup.esc="$event.target.value = ''"
          />
          <button
            v-else
            class="btn btn-primary btn-sm add-tag"
            @click="item.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="tag in item.tags"
            :key="tag"
            class="badge badge-warning"
            >{{ tag }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(item.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import axios from 'axios'
import MyTable from './MyTable'
export default {
  data() {
    return {
      goodsList: [],
    }
  },
  async created() {
    const res = await axios({
      method: 'get',
      url: 'https://www.escook.cn/api/goods',
    })
    console.log(res)
    const { status, data } = res.data
    if (status === 0) {
      this.goodsList = data
    }
  },
  components: {
    MyTable,
  },
  methods: {
    del(id) {
      this.goodsList = this.goodsList.filter((item) => item.id !== id)
    },
    LostFocus(item) {
      item.inputVisible = false
    },
    add(e, item) {
      console.log(item.id)
      if (e.target.value.trim() === '') return
      item.tags.push(e.target.value)
      e.target.value = ''
      item.inputVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.badge {
  margin-left: 5px;
}
</style>
